<?php
require_once 'autoload.php';
use OSS\OssClient;
use OSS\Core\OssException;

/**
 * 阿里云OSS API扩展库
 * Class Alioss
 */
class Alioss
{
    public $oss;    // OssClient

    private $_config = array(

        // ID和Secret查看：https://ak-console.aliyun.com/#/accesskey
        'accessKeyId'       => 'LTAICTgOqxl9CEad',
        'accessKeySecret'   => 'NLCLVi4Lqf3DRm39PeB1mrApaNITHD',

        // 【Bucket】未绑定域名：
        // Endpoint地区对照表：https://help.aliyun.com/document_detail/31837.html
        // isCName：false

        // 【Bucket】已绑定域名：
        // Endpoint：使用绑定域名
        // isCName：true （自定义域名时为True）
        'endpoint'          => 'img.zxkj918.com',
        'isCName'           => true,
        'bucket'            => 'zxkj-tourism'
    );

    public function __construct($config = array())
    {
        // Init Config
        if (!empty($config)) {
            $this->_config = $config;
        }

        // Init OssClient
        $this->oss = new OssClient(
            $this->_config['accessKeyId'],
            $this->_config['accessKeySecret'],
            $this->_config['endpoint'],
            $this->_config['isCName']
        );
    }

    /**
     * 获取Buckets列表
     * Endpoint类型为cname不能进行此操作
     *
     * @return array 返回bucket列表
     */
    public function get_buckets()
    {
        $result = array();

        try {
            $bucketListInfo = $this->oss->listBuckets();

            $bucketList = null;
            $bucketList = $bucketListInfo->getBucketList();
            foreach ($bucketList as $bucket) {
                $item = array();
                $item[] = $bucket->getLocation();
                $item[] = $bucket->getName();
                $item[] = $bucket->getCreatedate();

                $result[] = $item;
            }
        } catch (OssException $e) {
            return ['status' => false, 'msg' => $e->getMessage()];
        }

        return $result;
    }

    /**
     * 获取bucket的ACL配置情况
     *
     * @param string $bucket bucket名称，为空使用配置值
     * @param null $options 其他参数
     * @return string
     */
    public function get_bucket_acl($bucket = '', $options = NULL)
    {
        if (!empty($bucket)) {
            $bucket = $this->_config['bucket'];
        }
        return $this->oss->getBucketAcl($bucket, $options);
    }

    /**
     * 文件上传
     *
     * @param string $file_path 文件路径
     * @param string $file_name 文件名称
     * @param bool $auto_suffix 自动获取文件后缀
     * @return array
     */
    public function upload_file($file_path, $file_name = null, $auto_suffix = false)
    {
        $result = array();

        if (file_exists($file_path)) {
            // 若文件名不存在则采用文件md5值作为文件名
            if (empty($file_name)){
                $file_name = md5_file($file_path);
            }

            if ($auto_suffix) {
                // 获取文件后缀
                $file_suffix = $this->get_file_suffix($file_path);
                if (!empty($file_suffix)) {
                    // 获取文件名
                    if (empty($file_name)) {
                        $file_name = pathinfo($file_path, PATHINFO_FILENAME);
                    }
                    $name = $file_name . '.' . $file_suffix;
                }
            }

            if (empty($name)) {
                // 获取文件名(带后缀)
                if(empty($file_name)) {
                    $file_name = pathinfo($file_path, PATHINFO_BASENAME);
                }
                $name = $file_name;
            }

            try {
                // 上传文件
                $savePath = '/'.date('Ym').'/'.$name;
                $ossPath = 'uploads'.$savePath; //阿里云OSS路径
                $result = $this->oss->uploadFile($this->_config['bucket'], $ossPath, $file_path);

                if (!empty($result)) {
                    $cache = array();
                    $cache['x-oss-request-id'] = $result['x-oss-request-id'];
                    $cache['oss-request-url'] = $result['oss-request-url'];

                    $cache['url'] = $result['info']['url'];
                    $cache['method'] = $result['info']['method'];
                    $cache['etag'] = $result['etag'];
                    $cache['content_length'] = $result['info']['upload_content_length'];
                    $cache['save_path'] = $savePath;
                    $result = $cache;
                }

            } catch (OssException $e) {
                return ['status' => false, 'msg' => $e->getMessage()];
            }
        }
        return ['status' => true, 'msg' => $result];;
    }

    /**
     * 获取Object的Meta信息
     *
     * @param string $file_name 文件名
     * @return array
     */
    public function get_file_meta($file_name)
    {
        $result = array();
        if (!empty($file_name)) {
            try {
                $result = $this->oss->getObjectMeta($this->_config['bucket'], $file_name);
            } catch (OssException $e) {
//                printf($e->getMessage() . "\n");
            }
        }
        return $result;
    }

    /**
     * 检测Object是否存在
     *
     * @param string $file_name 文件名称，例：204.jpg
     * @return bool True|False
     */
    public function is_file_exist($file_name)
    {
        $result = false;
        if (!empty($file_name)) {
            $result = $this->oss->doesObjectExist($this->_config['bucket'], $file_name);
        }
        return $result;
    }

    /**
     * 获取文件后缀
     *
     * @param string $file_path 文件全路径
     * @param string $ret_mime 返回Mime信息 默认：False
     * @return string 后缀名，失败为空
     */
    public function get_file_suffix($file_path, $ret_mime = false)
    {
        $file_suffix = ''; // 文件后缀

        if (file_exists($file_path))
        {
            $file_mime = ''; // 文件Mime
            $fp = finfo_open(FILEINFO_MIME_TYPE);
            if($fp) {
                $file_mime = finfo_file($fp, $file_path);
                finfo_close($fp);
            }

            if($ret_mime) {
                return $file_mime;
            }

            switch ($file_mime) {
                case 'image/bmp':
                    $file_suffix = 'bmp';
                    break;
                case 'image/jpeg':
                    $file_suffix = 'jpg';
                    break;
                case 'image/png':
                    $file_suffix = 'png';
                    break;
                case 'image/gif':
                    $file_suffix = 'gif';
                    break;
                case 'image/ief':
                    $file_suffix = 'ief';
                    break;
                case 'image/svg+xml':
                    $file_suffix = 'svg';
                    break;
                case 'image/x-icon':
                    $file_suffix = 'ico';
                    break;
                case 'image/x-rgb':
                    $file_suffix = 'rgb';
                    break;

                // 文本文件
                case 'text/css':
                    $file_suffix = 'css';
                    break;
                case 'text/plain':
                    $file_suffix = 'txt';
                    break;
                case 'text/html':
                    $file_suffix = 'html';
                    break;
                case 'text/webviewhtml':
                    $file_suffix = 'htt';
                    break;
                case 'text/tab-separated-values':
                    $file_suffix = 'tsv';
                    break;

                // 视频文件
                case 'video/x-msvideo':
                    $file_suffix = 'avi';
                    break;
                case 'video/mpeg':
                    $file_suffix = 'mpeg';
                    break;
                case 'video/quicktime':
                    $file_suffix = 'mov';
                    break;
                case 'video/x-ms-asf':
                    $file_suffix = 'asx';
                    break;

                // 音频文件
                case 'audio/mpeg':
                    $file_suffix = 'mp3';
                    break;
                case 'audio/mid':
                    $file_suffix = 'mid';
                    break;

                // 应用文件
                case 'application/x-shockwave-flash':
                    $file_suffix = 'swf';
                    break;
                case 'application/vnd.ms-powerpoint':
                    $file_suffix = 'ppt';
                    break;
                case 'application/vnd.ms-excel':
                    $file_suffix = 'xls';
                    break;
                case 'application/msword':
                    $file_suffix = 'doc';
                    break;
                case 'application/postscript':
                    $file_suffix = 'ps';
                    break;
                case 'application/pdf':
                    $file_suffix = 'pdf';
                    break;
                case 'application/octet-stream':
                    $file_suffix = 'exe';
                    break;
                case 'application/zip':
                    $file_suffix = 'zip';
                    break;
            }
        }

        return strtolower($file_suffix);
    }

    /**
     * 获取阿里云路径
     * @param $filename
     * @return string
     */
    public function getAudioUrl($filename)
    {
        $timeout = 3600 * 7; //这个URL的有效期是3600秒
        $signedUrl = $this->oss->signUrl($this->_config['bucket'], trim($filename, '/'), $timeout);
        return $signedUrl;
    }
}